package settings_api

import (
	"errors"
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"muziai-server/conf"
	"muziai-server/core"
	"muziai-server/global"
	"muziai-server/utils/res"
	"os"
	"strings"
)

func (SettingsApi) SettingUpdateView(c *gin.Context) {

	name := c.Param("name")
	switch name {
	case "site_info":
		var cr conf.SiteInfo
		err := c.ShouldBindJSON(&cr)
		if err != nil {
			res.FailWithMsg(c, err.Error())
			return
		}
		// 如果修改了 project，seo，那么就要去判断前端的index.html是否存在
		err = UpdateWebIndexHtml(cr)
		if err != nil {
			logrus.Error(err)
			res.FailWithMsg(c, err.Error())
			return
		}
		global.Config.SiteInfo = cr

	case "ai":
		var cr conf.AI
		err := c.ShouldBindJSON(&cr)
		if err != nil {
			res.FailWithMsg(c, err.Error())
			return
		}
		global.Config.AI = cr
	case "wx_login":
		var cr conf.WxLogin
		err := c.ShouldBindJSON(&cr)
		if err != nil {
			res.FailWithMsg(c, err.Error())
			return
		}
		global.Config.WxLogin = cr
	case "alipay":
		var cr conf.Aalipay
		err := c.ShouldBindJSON(&cr)
		if err != nil {
			res.FailWithMsg(c, err.Error())
			return
		}
		global.Config.Aalipay = cr
	case "email":
		var cr conf.Email
		err := c.ShouldBindJSON(&cr)
		if err != nil {
			res.FailWithMsg(c, err.Error())
			return
		}
		global.Config.Email = cr
	case "sms":
		var cr conf.SMS
		err := c.ShouldBindJSON(&cr)
		if err != nil {
			res.FailWithMsg(c, err.Error())
			return
		}
		global.Config.SMS = cr
	case "ocr":
		var cr conf.Ocr
		err := c.ShouldBindJSON(&cr)
		if err != nil {
			res.FailWithMsg(c, err.Error())
			return
		}
		global.Config.Ocr = cr
	}
	core.SetYaml(global.Config)
	res.OkWithMsg(c, "更新站点信息成功")
	return
}

func UpdateWebIndexHtml(cr conf.SiteInfo) error {
	var judge bool
	if cr.Project.Title != "" {
		judge = true
	}
	if cr.Project.Icon != "" {
		judge = true
	}
	if cr.SEO.Keywords != "" {
		judge = true
	}
	if cr.SEO.Description != "" {
		judge = true
	}
	if cr.Project.WebPath != "" {
		judge = true
	}
	if !judge {
		// 关于project和SEO没有配置
		return nil
	}
	// 去判断这个文件是否存在
	if cr.Project.WebPath == "" {
		return errors.New("前端工程地址必填")
	}
	_, err := os.Stat(cr.Project.WebPath)
	if err != nil {
		if strings.Contains(err.Error(), "cannot") {
			return errors.New("前端工程文件不存在")
		}
		return err
	}
	file, err := os.Open(cr.Project.WebPath)
	if err != nil {
		return err
	}

	// 修改对应位置的内容，然后更新到index.html中
	//fmt.Println(string(byteData))
	doc, err := goquery.NewDocumentFromReader(file)
	if err != nil {
		return err
	}
	if cr.Project.Title != "" {
		doc.Find("title").SetText(cr.Project.Title)
	}
	if cr.Project.Icon != "" {
		selection := doc.Find("link[rel='icon']")
		if selection.Length() == 0 {
			// 没有找到
			doc.Find("head").AppendHtml(
				fmt.Sprintf("<link rel=\"icon\" sizes=\"any\" href=\"%s\">", cr.Project.Icon),
			)
		} else {
			selection.SetAttr("href", cr.Project.Icon)
		}
	}
	if cr.SEO.Keywords != "" {
		// <meta name="keywords" content="枫枫知道,枫枫知道个人博客,网站,开发,程序员,golang">
		selection := doc.Find("meta[name='keywords']")
		if selection.Length() == 0 {
			// 没有找到
			doc.Find("head").AppendHtml(
				fmt.Sprintf("<meta name=\"keywords\" content=\"%s\">", cr.SEO.Keywords),
			)
		} else {
			selection.SetAttr("content", cr.SEO.Keywords)
		}
	}
	if cr.SEO.Description != "" {
		// <meta name="description" content="枫枫知道个人博客9.0，全栈开发相关文章、并集成大语言模型，欢迎体验">
		selection := doc.Find("meta[name='description']")
		if selection.Length() == 0 {
			// 没有找到
			doc.Find("head").AppendHtml(
				fmt.Sprintf("<meta name=\"description\" content=\"%s\">", cr.SEO.Description),
			)
		} else {
			selection.SetAttr("content", cr.SEO.Description)
		}
	}

	html, err := doc.Html()
	if err != nil {
		return err
	}
	err = os.WriteFile(cr.Project.WebPath, []byte(html), 0666)
	if err != nil {
		return err
	}
	return nil

}
